<template>
  <header class="app-header">
    <div class="header-container">
      <!-- Logo和标题 -->
      <div class="header-left">
        <router-link to="/notes" class="logo-link">
          <el-icon size="24" class="logo-icon">
            <Document />
          </el-icon>
          <span class="app-title">{{ appTitle }}</span>
        </router-link>
      </div>

      <!-- 搜索框 (桌面端) -->
      <div class="header-center" v-if="!isMobile">
        <el-input
          v-model="searchQuery"
          placeholder="搜索笔记..."
          size="default"
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 用户操作区 -->
      <div class="header-right">
        <!-- 移动端搜索按钮 -->
        <el-button
          v-if="isMobile"
          type="text"
          :icon="Search"
          @click="showMobileSearch = true"
        />

        <!-- 新建笔记 -->
        <el-button
          type="primary"
          :icon="Plus"
          @click="createNewNote"
          size="default"
        >
          <span v-if="!isMobile">新建</span>
        </el-button>

        <!-- 用户菜单 -->
        <el-dropdown @command="handleUserAction" trigger="click">
          <span class="user-info">
            <el-avatar 
              :size="32" 
              :src="userAvatar" 
              class="user-avatar"
            >
              {{ userInitials }}
            </el-avatar>
            <span v-if="!isMobile" class="username">{{ authStore.user?.username }}</span>
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人资料
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                设置
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 移动端搜索抽屉 -->
    <el-drawer
      v-model="showMobileSearch"
      title="搜索笔记"
      direction="ttb"
      size="200px"
      :with-header="false"
    >
      <div class="mobile-search">
        <el-input
          v-model="searchQuery"
          placeholder="搜索笔记..."
          size="large"
          clearable
          autofocus
          @keyup.enter="handleMobileSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #suffix>
            <el-button
              type="text"
              @click="showMobileSearch = false"
            >
              取消
            </el-button>
          </template>
        </el-input>
      </div>
    </el-drawer>
  </header>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Search,
  Plus,
  User,
  Setting,
  SwitchButton,
  ArrowDown
} from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import { useNotesStore } from '../stores/notes'

const router = useRouter()
const authStore = useAuthStore()
const notesStore = useNotesStore()

// 响应式状态
const searchQuery = ref('')
const showMobileSearch = ref(false)
const windowWidth = ref(window.innerWidth)

// 计算属性
const appTitle = computed(() => import.meta.env.VITE_APP_TITLE || 'Web Notes')
const isMobile = computed(() => windowWidth.value < 768)

const userAvatar = computed(() => {
  // 这里可以实现头像逻辑，暂时返回空
  return ''
})

const userInitials = computed(() => {
  const username = authStore.user?.username
  if (!username) return 'U'
  return username.charAt(0).toUpperCase()
})

// 窗口大小监听
const handleResize = () => {
  windowWidth.value = window.innerWidth
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 搜索处理
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    notesStore.searchNotes(searchQuery.value.trim())
    router.push('/notes')
  }
}

const handleMobileSearch = () => {
  handleSearch()
  showMobileSearch.value = false
}

// 新建笔记
const createNewNote = () => {
  router.push('/editor')
}

// 用户操作处理
const handleUserAction = async (command: string) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人资料功能开发中...')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        authStore.logout()
        ElMessage.success('已退出登录')
        router.push('/auth')
      } catch {
        // 用户取消操作
      }
      break
  }
}
</script>

<style scoped>
.app-header {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.logo-link {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: var(--el-text-color-primary);
  transition: color 0.3s ease;
}

.logo-link:hover {
  color: var(--el-color-primary);
}

.logo-icon {
  color: var(--el-color-primary);
  margin-right: 8px;
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  margin-left: 4px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  max-width: 400px;
  margin: 0 24px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background-color: var(--el-bg-color-page);
}

.user-avatar {
  background: var(--el-color-primary);
  color: white;
  font-weight: 600;
}

.username {
  font-size: 14px;
  color: var(--el-text-color-primary);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dropdown-icon {
  font-size: 12px;
  color: var(--el-text-color-regular);
  transition: transform 0.3s ease;
}

.user-info:hover .dropdown-icon {
  transform: translateY(1px);
}

.mobile-search {
  padding: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 12px;
    height: 56px;
  }
  
  .app-title {
    font-size: 16px;
  }
  
  .header-right {
    gap: 8px;
  }
  
  .username {
    display: none;
  }
}

@media (max-width: 480px) {
  .header-container {
    padding: 0 8px;
  }
  
  .logo-icon {
    margin-right: 6px;
  }
  
  .app-title {
    font-size: 15px;
  }
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
}
</style>